﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using iTextSharp;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.html;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Data.SqlClient;

namespace CTEA_INDIA
{
    public partial class portView : System.Web.UI.Page
    {
        DataSet dsPhotosFiles = new DataSet();

        PagedDataSource pgsource = new PagedDataSource();
        int findex, lindex;
        DataRow dr;
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["Cat"] = Request.QueryString["type"];
            BAL.conn.connectionString = ConfigurationManager.ConnectionStrings["CTEA"].ConnectionString;
            if (!IsPostBack)
            {

                Session["Cat"] = Request.QueryString["type"];
                populateArtistCard();
                BAL.Customers.PopulateLoc(ref cmbEdtLocation);
            }
            if (Session["UserID"] == null)
            {
                Response.Redirect("Default.aspx");
            }

            

            string[] Details = BAL.Customers.GetMaxArtistCardId();

            int genVal = Details[0].ToString().Count();
            int idNo = Convert.ToInt32(Details[0]) + 1;
            string memno = "";

            if (genVal == 1)
            {
                memno = "MN00000" + idNo.ToString();
            }
            else if (genVal == 2)
            {
                memno = "MN0000" + idNo.ToString();
            }
            else if (genVal == 3)
            {
                memno = "MN000" + idNo.ToString();
            }
            else if (genVal == 4)
            {
                memno = "MN00" + idNo.ToString();
            }
            else if (genVal == 5)
            {
                memno = "MN0" + idNo.ToString();
            }
            else if (genVal == 6)
            {
                memno = "MN" + idNo.ToString();
            }

        }



        protected void Page_Init(object sender, EventArgs e)
        {

            if (Session["dsPhotoFiles"] == null)
            {
                this.initPhotoDS();
                Session.Add("dsPhotoFiles", dsPhotosFiles);
            }
            else
            {
                dsPhotosFiles = (DataSet)Session["dsPhotoFiles"];
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                // Get the HttpFileCollection
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
                          System.IO.Path.GetFileName(hpf.FileName));
                        Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " +
                            hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        //protected void btnUploadFiles_Click(object sender, EventArgs e)
        //{
        //}

        private void initPhotoDS()
        {
            dsPhotosFiles.Tables.Add("Photos");
            dsPhotosFiles.Tables[0].Columns.Add("fileBytes", Type.GetType("System.Byte[]"));
            dsPhotosFiles.Tables[0].Columns.Add("filePath");
            dsPhotosFiles.Tables[0].Columns.Add("fileDesc");
            dsPhotosFiles.Tables[0].Columns.Add("id");
        }

        protected void lnkBtnRemovePhoto_Command(object sender, CommandEventArgs e)
        {

            foreach (DataRow dr in dsPhotosFiles.Tables[0].Rows)
            {
                if (dr["id"].ToString() == e.CommandArgument.ToString())
                {
                    dsPhotosFiles.Tables[0].Rows.Remove(dr);
                    break;
                }

            }

        }


        protected void ViewCard(object sender, EventArgs e)
        {
            LinkButton lnkVw = sender as LinkButton;
            GridViewRow row = (GridViewRow)lnkVw.Parent.Parent;
            // int locationID = Convert.ToInt32(ddlLocation.SelectedValue);


            //int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);
            LinkButton lnkview = (LinkButton)sender;
            DataListItem dlitem = (DataListItem)lnkview.Parent;
            int Cid = Convert.ToInt32(DataList1.DataKeys[dlitem.ItemIndex]);


            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);

            GeneratePDF(Details);

        }

        protected void lnkView_Click(object sender, EventArgs e)
        {
            LinkButton lnkVw = sender as LinkButton;
            GridViewRow row = (GridViewRow)lnkVw.Parent.Parent;
            // int locationID = Convert.ToInt32(ddlLocation.SelectedValue);


            //int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);


            LinkButton lnkview = (LinkButton)sender;
            DataListItem dlitem = (DataListItem)lnkview.Parent;
            int Cid = Convert.ToInt32(DataList1.DataKeys[dlitem.ItemIndex]);

            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);

            lblViewName.Text = Details[2];
            lblViewLocation.Text = Details[3];
            lblViewType.Text = Details[4];
            lblViewCategory.Text = Details[5];
            lblViewDOB.Text = Details[6];
            lblViewVF.Text = Details[7];
            lblViewVT.Text = Details[8];
            lblViewEMail.Text = Details[9];
            lblViewRefName.Text = Details[10];
            lblVIewRefCon.Text = Details[11];
            lblViewIdProof.Text = Details[15];
            lblViewAddrProof.Text = Details[16];
            lblViewAmount.Text = Details[17];

            int UserId = Cid;
            DataSet Imgs = BAL.Customers.GetImg(UserId);

            if (Imgs.Tables[0].Rows.Count > 0)
            {

                phdImgGallry.Controls.Add(new LiteralControl("<fieldset><legend>Pictures</legend><table><tr>"));

                foreach (DataRow nm in Imgs.Tables[0].Rows)
                {

                    phdImgGallry.Controls.Add(new LiteralControl("<td><a href=\"Portfolio/" + nm["Picture"] + "\"   rel=\"enlargeimage\" rev=\"targetdiv:loadarea2,trigger:mouseover\" target=\"_blank\"  title=\"my caption\"> <img id=\"imagebox\" style=\"width: 120px; height: 120px; border: none;\" alt=\"\" class=\"magnify\" data-magnifyby=\"2\" src=\"Portfolio/" + nm["Picture"] + "\" /></a></td>"));
                }

                phdImgGallry.Controls.Add(new LiteralControl("</tr></table></fieldset>"));


            }






            lnkView_ModalPopupExtender.Show();

            //document.getElementById("totalDaystd").innerHTML = "<asp:TextBox ID=\"txtDaysText\" runat=\"server\" ReadOnly=\"True\" Text=\""+ days +"\"></asp:TextBox>";

        }


        protected void lnkEdit_Click(object sender, EventArgs e)
        {
            //LinkButton lnkEdit = sender as LinkButton;
            //GridViewRow row = (GridViewRow)lnkEdit.Parent.Parent;

            //int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);

            LinkButton lnkview = (LinkButton)sender;
            DataListItem dlitem = (DataListItem)lnkview.Parent;
            int Cid = Convert.ToInt32(DataList1.DataKeys[dlitem.ItemIndex]);


            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);
            ViewState["Artist_Card_Id"] = Details[0];


            txtEdtName.Text = Details[2];
            cmbEdtLocation.Text = Details[3];
            cmbEdtType.Text = Details[4];
            cmbEdtCategory.Text = Details[5];
            txtEdtBDate.Text = Details[6];
            txtEdtValidFrom.Text = Details[7];
            txtEdtValidTill.Text = Details[8];
            txtEdtEmail.Text = Details[9];
            txtEdtRefName.Text = Details[10];
            txtEdtRefCon.Text = Details[11];
            txtEdtGroup.Text = Details[21];
            LnkEditPopUp.Show();

        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            //LinkButton lnkEdit = sender as LinkButton;
            //GridViewRow row = (GridViewRow)lnkEdit.Parent.Parent;

            //int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);
            LinkButton lnkview = (LinkButton)sender;
            DataListItem dlitem = (DataListItem)lnkview.Parent;
            int Cid = Convert.ToInt32(DataList1.DataKeys[dlitem.ItemIndex]);


            BAL.Customers.DeleteArtistCardById(Cid);
            populateArtistCard();
        }

        protected void update(object sender, EventArgs e)
        {
            string Name = txtEdtName.Text;
            string Loc = cmbEdtLocation.Text;
            string Addresss = txtEdtGroup.Text;
            string ArtsType = cmbEdtType.Text;
            string Category = cmbEdtCategory.Text;
            string Techni_Type = cmbEdtTechType.Text;
            string Date = txtEdtBDate.Text;
            string Validfrom = txtEdtValidFrom.Text;
            string validTo = txtEdtValidTill.Text;
            string Email = txtEdtEmail.Text;
            string RefName = txtEdtRefName.Text;
            string ContctNo = txtEdtRefCon.Text;
            string ID = ViewState["Artist_Card_Id"].ToString();
            string Group = txtEdtGroup.Text;
            BAL.Customers.UpdateArtistCardInfo(Name, Loc, Addresss, ArtsType, Category, Techni_Type, Date, Validfrom, validTo,
                 Email, RefName, ContctNo, ID, Group);

            populateArtistCard();
        }

        public void populateArtistCard()
        {

            DataSet ds = BAL.Customers.viewAllArtistPort(Session["Cat"].ToString());
            //gdArtistCard.DataSource = ds;
            //gdArtistCard.DataBind();
            pgsource.DataSource = ds.Tables[0].DefaultView;
            pgsource.PageSize = 10;



            //Get Current Page Index
            pgsource.CurrentPageIndex = CurrentPage;

            //Store it Total pages value in View state
            ViewState["totpage"] = pgsource.PageCount;

            //Below line is used to show page number based on selection like "Page 1 of 20"
            lblpage.Text = "Page " + (CurrentPage + 1) + " of " + pgsource.PageCount;

            //Enabled true Link button previous when current page is not equal first page 
            //Enabled false Link button previous when current page is first page
            lnkPrevious.Enabled = !pgsource.IsFirstPage;

            //Enabled true Link button Next when current page is not equal last page 
            //Enabled false Link button Next when current page is last page
            lnkNext.Enabled = !pgsource.IsLastPage;

            //Enabled true Link button First when current page is not equal first page 
            //Enabled false Link button First when current page is first page
            lnkFirst.Enabled = !pgsource.IsFirstPage;

            //Enabled true Link button Last when current page is not equal last page 
            //Enabled false Link button Last when current page is last page
            lnkLast.Enabled = !pgsource.IsLastPage;

            //Bind resulted PageSource into the DataList
            DataList1.DataSource = pgsource;
            DataList1.DataBind();

            //Create Paging in the second DataList "DataListPaging"
            doPaging();




            //DataList1.DataSource = ds;
            //DataList1.DataBind();

        }

        //protected void gdArtistCard_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //{
        //    gdArtistCard.PageIndex = e.NewPageIndex;
        //    populateArtistCard();
        //}

        //protected void gdArtistCard_RowDataBound(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        LinkButton lEdit = (LinkButton)e.Row.FindControl("lnkEdit");
        //        Button update = (Button)e.Row.FindControl("btnUpdate");
        //        LinkButton lDelete = (LinkButton)e.Row.FindControl("lnkDelete");
        //        lDelete.CommandArgument = e.Row.RowIndex.ToString();
        //        LinkButton lnkApp = (LinkButton)e.Row.FindControl("lnkApprove");



        //    }

        //}

        public object UserId { get; set; }
        


        public void GeneratePDF(string[] Details)
        {





            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 60, 60, 60, 60);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath("~/IdCards/" + string.Format("Card-{0}.pdf", Details[0])), FileMode.Create, FileAccess.Write));

            string notice = "Help Line : +91 22 256 77777";
            // string ToInvoice = Address;
            string contents = File.ReadAllText(Server.MapPath("~/Card.htm"));

            contents = contents.Replace("[NAME]", Details[2]);
            contents = contents.Replace("[ARTISTGROUP]", Details[5]);
            contents = contents.Replace("[ARTISTCATEGORY]", Details[5]);
            contents = contents.Replace("[DOB]", DateTime.Parse(Details[6]).ToShortDateString());
            contents = contents.Replace("[GENDER]", Details[4]);
            contents = contents.Replace("[VALIDFROM]", DateTime.Parse(Details[7]).ToShortDateString());
            DateTime dt = new DateTime();
            dt = DateTime.Parse(Details[7]);
            int day = dt.Day;
            int mon = dt.Month;
            int yr = dt.Year + 1;
            DateTime vd = new DateTime(yr, mon, day);

            contents = contents.Replace("[VALIDTILL]", vd.ToShortDateString());

            int genVal = Details[0].ToString().Count();
            string memno = "";

            if (genVal == 1)
            {
                memno = "MN00000" + Details[0].ToString();
            }
            else if (genVal == 2)
            {
                memno = "MN0000" + Details[0].ToString();
            }
            else if (genVal == 3)
            {
                memno = "MN000" + Details[0].ToString();
            }
            else if (genVal == 4)
            {
                memno = "MN00" + Details[0].ToString();
            }
            else if (genVal == 5)
            {
                memno = "MN0" + Details[0].ToString();
            }
            else if (genVal == 6)
            {
                memno = "MN" + Details[0].ToString();
            }

            contents = contents.Replace("[MEMBERSHIPNO]", memno);


            // Step 4: Parse the HTML string into a collection of elements...

            pdfDoc.Open();



            var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/candy-gloss.png"));
            logo.SetAbsolutePosition(100, 770);
            logo.ScaleAbsolute(450, 70);


            pdfDoc.Add(logo);
            var IDimage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/" + Details[14] + ""));
            //var IDimage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/idimag.jpg"));
            logo.SetAbsolutePosition(110, 630);
            logo.ScaleAbsolute(140, 120);
            pdfDoc.Add(logo);
            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);

            // pdfDoc.HtmlStyleClass = "table";

            foreach (var htmlElement in parsedHtmlElements)
            {
                pdfDoc.Add(htmlElement as IElement);
            }

            htmlparser.Parse(sr);

            pdfDoc.Close();

            string path = "~/IdCards/" + string.Format("Card-{0}.pdf", Details[0]);

            Response.Redirect(path);

        }

        protected void LinkButton1_Click(object sender, EventArgs e) // view

        {
            LinkButton lnkview = (LinkButton)sender;
            DataListItem dlitem = (DataListItem)lnkview.Parent;            
            int Cid = Convert.ToInt32( DataList1.DataKeys[dlitem.ItemIndex]);



            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);

            lblViewName.Text = Details[2];
            lblViewLocation.Text = Details[3];
            lblViewType.Text = Details[4];
            lblViewCategory.Text = Details[5];
            lblViewDOB.Text = Details[6];
            lblViewVF.Text = Details[7];
            lblViewVT.Text = Details[8];
            lblViewEMail.Text = Details[9];
            lblViewRefName.Text = Details[10];
            lblVIewRefCon.Text = Details[11];
            lblViewIdProof.Text = Details[15];
            lblViewAddrProof.Text = Details[16];
            lblViewAmount.Text = Details[17];

            int UserId = Cid;
            DataSet Imgs = BAL.Customers.GetImg(UserId);

            if (Imgs.Tables[0].Rows.Count > 0)
            {

                phdImgGallry.Controls.Add(new LiteralControl("<fieldset><legend>Pictures</legend><table><tr>"));

                foreach (DataRow nm in Imgs.Tables[0].Rows)
                {

                    phdImgGallry.Controls.Add(new LiteralControl("<td><a href=\"Portfolio/" + nm["Picture"] + "\"   rel=\"enlargeimage\" rev=\"targetdiv:loadarea2,trigger:mouseover\" target=\"_blank\"  title=\"my caption\"> <img id=\"imagebox\" style=\"width: 120px; height: 120px; border: none;\" alt=\"\" class=\"magnify\" data-magnifyby=\"2\" src=\"Portfolio/" + nm["Picture"] + "\" /></a></td>"));
                }

                phdImgGallry.Controls.Add(new LiteralControl("</tr></table></fieldset>"));


            }


            lnkView_ModalPopupExtender.Show();

        }


        /////////////
        private void doPaging()
        {
            DataTable dt = new DataTable();
            //Add two column into the DataTable "dt" 
            //First Column store page index default it start from "0"
            //Second Column store page index default it start from "1"
            dt.Columns.Add("PageIndex");
            dt.Columns.Add("PageText");

            //Assign First Index starts from which number in paging data list
            findex = CurrentPage - 5;

            //Set Last index value if current page less than 5 then last index added "5" values to the Current page else it set "10" for last page number
            if (CurrentPage > 5)
            {
                lindex = CurrentPage + 5;
            }
            else
            {
                lindex = 10;
            }

            //Check last page is greater than total page then reduced it to total no. of page is last index
            if (lindex > Convert.ToInt32(ViewState["totpage"]))
            {
                lindex = Convert.ToInt32(ViewState["totpage"]);
                findex = lindex - 10;
            }

            if (findex < 0)
            {
                findex = 0;
            }

            //Now creating page number based on above first and last page index
            for (int i = findex; i < lindex; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dt.Rows.Add(dr);
            }

            //Finally bind it page numbers in to the Paging DataList
            DataListPaging.DataSource = dt;
            DataListPaging.DataBind();
        }

        private int CurrentPage
        {
            get
            {   //Check view state is null if null then return current index value as "0" else return specific page viewstate value
                if (ViewState["CurrentPage"] == null)
                {
                    return 0;
                }
                else
                {
                    return ((int)ViewState["CurrentPage"]);
                }
            }
            set
            {
                //Set View statevalue when page is changed through Paging DataList
                ViewState["CurrentPage"] = value;
            }
        }

        protected void DataListPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("newpage"))
            {
                //Assign CurrentPage number when user click on the page number in the Paging DataList
                CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
                //Refresh DataList "DlistEmp" Data once user change page
                          populateArtistCard();
            }
        }

        protected void lnkFirst_Click(object sender, EventArgs e)
        {
            //If user click First Link button assign current index as Zero "0" then refresh DataList "DlistEmp" Data.
            CurrentPage = 0;
            populateArtistCard();
        }

        protected void lnkLast_Click(object sender, EventArgs e)
        {
            //If user click Last Link button assign current index as totalpage then refresh DataList "DlistEmp" Data.
            CurrentPage = (Convert.ToInt32(ViewState["totpage"]) - 1);
            populateArtistCard();
        }

        protected void lnkPrevious_Click(object sender, EventArgs e)
        {
            //If user click Previous Link button assign current index as -1 it reduce existing page index.
            CurrentPage -= 1;
            //refresh DataList "DlistEmp" Data
            populateArtistCard();
        }

        protected void lnkNext_Click(object sender, EventArgs e)
        {
            //If user click Next Link button assign current index as +1 it add one value to existing page index.
            CurrentPage += 1;

            //refresh DataList "DlistEmp" Data
            populateArtistCard();
        }

      
        protected void DataListPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            //Enabled False for current selected Page index
            LinkButton lnkPage = (LinkButton)e.Item.FindControl("Pagingbtn");
            if (lnkPage.CommandArgument.ToString() == CurrentPage.ToString())
            {
                lnkPage.Enabled = false;
            }
        }

  

    }
}